package com.studyweb.service.impl;

import com.studyweb.pojo.entity.PoliticsQuestion;
import com.studyweb.mapper.PoliticsQuestionMapper;
import com.studyweb.service.PoliticsQuestionService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 时政题目服务实现类
 */
@Slf4j
@Service
public class PoliticsQuestionServiceImpl implements PoliticsQuestionService {
    
    @Autowired
    private PoliticsQuestionMapper politicsQuestionMapper;
    
    @Override
    public Map<String, Object> getQuestions(int pageNum, int pageSize, String questionType, String difficulty, String category, String subCategory, String keyword, String orderBy, String orderType) {
        // 使用PageHelper进行分页
        PageHelper.startPage(pageNum, pageSize);
        
        // 处理排序参数
        if (orderBy != null && orderType != null) {
            PageHelper.orderBy(orderBy + " " + orderType);
        }
        
        // 使用selectQuestions方法进行分页查询，只需要传递查询条件参数
        List<PoliticsQuestion> questions = politicsQuestionMapper.selectQuestions(
            0, 0, questionType, difficulty, category, subCategory, keyword, orderBy, orderType);
        int total = politicsQuestionMapper.countQuestions(questionType, difficulty, category, subCategory, keyword);
        
        Map<String, Object> result = new HashMap<>();
        result.put("questions", questions);
        result.put("total", total);
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
        result.put("totalPages", (total + pageSize - 1) / pageSize);
        
        return result;
    }
    
    @Override
    public PoliticsQuestion createQuestion(PoliticsQuestion question) {
        try {
            question.setCreateTime(LocalDateTime.now());
            question.setUpdateTime(LocalDateTime.now());
            question.setStatus(1); // 1-正常状态
            
            // 确保questionId为null，让数据库自动生成
            question.setQuestionId(null);
            
            int result = politicsQuestionMapper.insert(question);
            if (result > 0) {
                return question; // 返回包含ID的题目对象
            }
            return null;
        } catch (Exception e) {
            log.error("创建时政题目失败：{}", e.getMessage(), e);
            return null;
        }
    }
    
    @Override
    public PoliticsQuestion getQuestionById(Long id) {
        try {
            return politicsQuestionMapper.selectById(id);
        } catch (Exception e) {
            log.error("获取时政题目详情失败：{}", e.getMessage(), e);
            return null;
        }
    }
    
    @Override
    public boolean updateQuestion(PoliticsQuestion question) {
        try {
            question.setUpdateTime(LocalDateTime.now());
            int result = politicsQuestionMapper.updateById(question);
            return result > 0;
        } catch (Exception e) {
            log.error("更新时政题目失败：{}", e.getMessage(), e);
            return false;
        }
    }
    
    @Override
    public boolean deleteQuestion(Long id) {
        try {
            // 物理删除，直接从数据库中删除记录
            int result = politicsQuestionMapper.deleteById(id);
            return result > 0;
        } catch (Exception e) {
            log.error("删除时政题目失败：{}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean batchDeleteQuestions(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        try {
            int deletedCount = politicsQuestionMapper.batchDeleteByIds(ids);
            return deletedCount == ids.size();
        } catch (Exception e) {
            log.error("批量删除时政题目失败：{}", e.getMessage(), e);
            return false;
        }
    }
    
    @Override
    public List<PoliticsQuestion> getPracticeQuestions(int count, String difficulty, String category, String subCategory, String questionType) {
        try {
            // 默认按照question_id升序排列
            return getPracticeQuestions(count, difficulty, category, subCategory, questionType, "question_id", "asc");
        } catch (Exception e) {
            log.error("获取练习题目失败：{}", e.getMessage(), e);
            return null;
        }
    }
    
    // 添加一个新的重载方法，支持自定义排序
    public List<PoliticsQuestion> getPracticeQuestions(int count, String difficulty, String category, String subCategory, String questionType, String orderBy, String orderType) {
        try {
            // 如果count大于0，使用PageHelper进行分页
            if (count > 0) {
                PageHelper.startPage(1, count);
            }
            
            return politicsQuestionMapper.selectPracticeQuestions(0, difficulty, category, subCategory, questionType, orderBy, orderType);
        } catch (Exception e) {
            log.error("获取练习题目失败：{}", e.getMessage(), e);
            return null;
        }
    }
    
    @Override
    public Map<String, Object> submitAnswer(Map<String, Object> answerData) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 这里应该实现答题逻辑
            // 1. 验证答案
            // 2. 记录答题记录
            // 3. 更新统计信息
            
            result.put("correct", true);
            result.put("score", 100);
            result.put("message", "答题成功");
            
            return result;
        } catch (Exception e) {
            log.error("提交答案失败：{}", e.getMessage(), e);
            result.put("correct", false);
            result.put("message", "答题失败");
            return result;
        }
    }
    
    @Override
    public Map<String, Object> getResults(int pageNum, int pageSize) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 这里应该实现获取答题结果的逻辑
            // 从答题记录表中获取数据
            
            result.put("results", new ArrayList<>());
            result.put("total", 0);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            
            return result;
        } catch (Exception e) {
            log.error("获取答题结果失败：{}", e.getMessage(), e);
            return result;
        }
    }
}